package br.ucb.cesbdao.persistencia.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;

import br.ucb.cesbdao.persistencia.AbstractConnectionDAO;
import br.ucb.cesbdao.persistencia.factory.FactoryConnection;
import br.ucb.cesbdao.servicos.DateUtil;
import br.ucb.cesbdao.servicos.TimeUtil;

public class NaoAgendadoDAO extends AbstractConnectionDAO{
	
	public static final String BUSCA_NAO_AGENDADOS_HOJE = "SELECT COUNT(*) AS cont FROM dao_nao_agendado WHERE data = ?;";
	public static final String ADICIONA_NAO_AGENDADOS	= "INSERT INTO dao_nao_agendado VALUES(?,?);";
	public static final String DELETA_NAO_AGENDADOS 	= "DELETE from dao_nao_agendado WHERE data = ? order by hora desc limit 1;";
	public static final String ATUALIZA_NAO_AGENDADOS 	= "UPDATE dao_nao_agendado set qnt_n_agendada = ? WHERE data = ?;";
	private static final java.sql.Date DATA_ATUAL 			= new java.sql.Date(DateUtil.getDataAtual().getTime());
	
	public NaoAgendadoDAO(Connection con) {
		super(con);
	}
	
	public  int getToday() throws ClassNotFoundException, SQLException {
		PreparedStatement stm = getConexao().prepareStatement(BUSCA_NAO_AGENDADOS_HOJE);		
		stm.setDate(1, DATA_ATUAL);
		ResultSet rs = stm.executeQuery();
		if(rs.first()){
			int qnd = rs.getInt("cont");
			FactoryConnection.getInstance().closeConexao(stm, rs);
			return qnd;
		}
		return -1;
			
	}

	public  void add() throws ClassNotFoundException, SQLException {
		PreparedStatement stm = getConexao().prepareStatement(ADICIONA_NAO_AGENDADOS);
		stm.setTime(1,Time.valueOf(TimeUtil.getHoraSys()));
		stm.setDate(2, DATA_ATUAL);
		stm.execute();
		FactoryConnection.getInstance().closeConexao(stm);
	}

	public  void update(int qnt) throws SQLException, ClassNotFoundException {
		PreparedStatement stm = getConexao().prepareStatement(ATUALIZA_NAO_AGENDADOS);
		stm.setInt(1, qnt);
		stm.setDate(2, DATA_ATUAL);
		stm.executeUpdate();
		FactoryConnection.getInstance().closeConexao(stm);
		
	}

	public  void dell() throws SQLException, ClassNotFoundException {
		PreparedStatement stm = getConexao().prepareStatement(DELETA_NAO_AGENDADOS);
		stm.setDate(1, DATA_ATUAL);
		stm.execute();
		FactoryConnection.getInstance().closeConexao(stm);
	}
	
}
